# *_*coding:utf-8 *_*
# @Author : Reggie
# @Time : 2022/9/3 19:45
from functools import partial
from pathlib import Path
from urllib.parse import urlparse

from m3u8 import M3U8

from base_m3u8 import aes_decode, get_natsorted_files, merge_ts


def t_aes_decode():
    file_path = r"C:\Users\wt\Project\PersonProject\PyProject\m3u8_download\.tmp\.cache\m3u8\56cd739313f5e35c724b974551918348.m3u8"
    with open(file_path, encoding="utf-8") as fileobj:
        content = fileobj.read().strip()
    m3u8_url = "https://m3u8.zztt85.com/watch9/0513720b73de646a1215a0d3d6c538cc/0513720b73de646a1215a0d3d6c538cc.m3u8"
    url_parse = urlparse(m3u8_url)
    base_uri = f"{url_parse.scheme}://{url_parse.netloc}"
    m3u8 = M3U8(
        content=content,
        base_path=None,
        base_uri=base_uri,
        strict=None,
        custom_tags_parser=None,
    )
    iv = m3u8.keys[0].iv
    real_iv = iv
    if iv.startswith("0x"):
        real_iv = iv[2:18]
    key = b'[\x85\x1bu\x85t\x01\x1a\x15BE\xad\xb7<B.'
    decode = partial(aes_decode, key=key, iv=real_iv.encode('utf-8'))
    ts_path = r"C:\Users\wt\Project\PersonProject\PyProject\tmp\56cd739313f5e35c724b974551918348.ts"
    real_ts_path = Path(ts_path).joinpath("decode")
    # for filepath in Path(
    #         ts_path).iterdir():
    #     current_file_path = Path(filepath)
    #     current_file_path = Path(filepath)
    #     with open(current_file_path, 'rb') as ft:
    #         scline = decode(ft.read())
    #     decode_path = current_file_path.parent.joinpath("decode")
    #     decode_path.mkdir(parents=True, exist_ok=True)
    #     decode_file_path = decode_path.joinpath(current_file_path.name)
    #     with open(decode_file_path, 'wb') as fn:
    #         fn.write(scline)
    out_path = r"C:\download\zztt24"
    file_name = r"56cd739313f5e35c724b974551918348"

    merge_ts(
        get_natsorted_files(real_ts_path),
        out_path,
        file_name,
        decode=decode
    )


if __name__ == '__main__':
    t_aes_decode()
